import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Input, message, Popover, Icon } from 'antd';
import { editPassiveDetection } from '@api/passiveDetection';
import { IP_RE, IP_INTERVAL_RE, CIDR_RE } from '@util/constants';
import _ from 'lodash';
import './index.less';

const prefixCls = 'passive-detection-modal';
const TextArea = Input.TextArea;
const description =
  '请输入IP地址或者IP段格式，多个目标用换行符分隔，可根据个人习惯选择下面任意格式：\r\n格式1：192.168.1.1\r\n格式2：192.168.1.1-192.168.1.255\r\n格式3：192.169.1.0/24';

class PassiveDetectionModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      id: '',
      filterCondition: [],
      ip: ''
    };
  }

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(props) {
    if (props.visible) {
      let { ip = '', name = '', _id: id = '', filterCondition } = props.data;
      this.setState({ name, ip, filterCondition, id });
    }
  }

  onNameChange = e => {
    this.setState({ name: e.target.value });
  };

  onfilterConditionChange = e => {
    const value = e.target.value;
    const filterCondition = value ? _.split(value, '\n') : [];
    let filterConditionError = '';
    const formatError = _.some(filterCondition, target => {
      return !IP_RE.test(target) && !IP_INTERVAL_RE.test(target) && !CIDR_RE.test(target);
    });

    if (formatError) {
      filterConditionError = '筛选目标存在格式错误';
    }
    this.setState({ filterCondition, filterConditionError });
  };

  onSubmit = () => {
    const { onClose, loadList } = this.props;
    let { name, filterCondition, id, filterConditionError, ip } = this.state;
    if (filterConditionError) {
      return;
    }
    const body = { name, filterCondition, ip };
    if (id) {
      body['id'] = id;
    }
    editPassiveDetection(body)
      .then(() => {
        loadList();
        onClose();
        message.success('编辑成功');
      })
      .catch(res => {
        let errMsg = _.get(res, 'message', '');
        errMsg = errMsg ? errMsg : '编辑失败';
        message.error(errMsg);
      });
  };

  render() {
    const { visible, onClose } = this.props;
    const { ip, name, filterCondition, filterConditionError } = this.state;
    return (
      <Modal
        maskClosable={false}
        title={'编辑被动探测引擎'}
        visible={visible}
        className={prefixCls}
        onOk={this.onSubmit}
        onCancel={onClose}
      >
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>被动探测引擎地址</div>
          <div className={`${prefixCls}-item-content ${prefixCls}-item-ip`}>{ip}</div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>名称</div>
          <div className={`${prefixCls}-item-content`}>
            <Input placeholder="请输自定义名称" value={name} onChange={this.onNameChange} />
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>
            筛选目标
            <Popover
              overlayStyle={{ width: 270 }}
              content={
                '系统如果从流量中发现筛选目标中的IP，会自动更新到资产管理列表；如果不设置筛选目标，系统会将从流量中解析到的所有IP更新到资产管理列表。'
              }
            >
              <Icon type="info-circle" style={{ marginLeft: 4, color: '#999EA8' }} />
            </Popover>
          </div>
          <div className={`${prefixCls}-item-content`}>
            <TextArea
              className={`${prefixCls}-ips`}
              value={_.join(filterCondition, '\n')}
              rows={5}
              placeholder={description}
              onChange={this.onfilterConditionChange}
            />
            <span style={{ color: 'red' }}>{filterConditionError}</span>
          </div>
        </div>
      </Modal>
    );
  }
}

PassiveDetectionModal.propTypes = {
  onClose: PropTypes.func,
  loadList: PropTypes.func,
  visible: PropTypes.bool,
  data: PropTypes.object
};

export default PassiveDetectionModal;
